<?php

namespace Home\Controller;

use Think\Controller;
use Home\Service\WeixinAPIService;
use Home\Service\ExpressService;

/**
 * 首页Controller
 *
 * @author 李静波
 *        
 */
class IndexController extends PSIBaseController {

	/**
	 * 首页
	 */
	public function index() {
		$ws = new WeixinAPIService();
		
		$code = I("get.code");
		
		if ($code) {
			// 已经获得微信登录授权
			
			$openId = $ws->getOpenId($code);
			
			$ws->setOpenIdIntoSession($openId);
			
			$this->initVar();
			
			$this->assign("title", "首页");
			
			$this->display();
		} else {
			// 登录微信
			
			$config = $ws->getWeixinConfig();
			$appId = $config["appId"];
			$appSecret = $config["appSecret"];
			
			$isReleased = $config["isReleased"];
			
			if ($isReleased == 1) {
				// 在实际应用中，redirectURI就应该是本方法对应的地址
				$redirectURI = $config["redirectURI"];
				
				$url = "https://open.weixin.qq.com/connect/oauth2/authorize?";
				$url .= "appid=$appId&redirect_uri=$redirectURI&response_type=code";
				$url .= "&scope=snsapi_base&state=STATE#wechat_redirect";
				
				redirect($url);
			} else {
				// 本地开发环境
				$ws->setOpenIdIntoSession($ws->genLocalMockOpenId());
				
				$this->initVar();
				
				$this->assign("title", "首页");
				
				$this->display();
			}
		}
	}

	/**
	 * 关于
	 */
	public function about() {
		$ws = new WeixinAPIService();
		$openId = $ws->getOpenIdFromSession();
		
		if ($openId) {
			$this->initVar();
			
			$this->assign("title", "关于");
			
			$this->display();
		} else {
			redirect(__ROOT__ . "/Home");
		}
	}

	/**
	 * 我 - 主页面
	 */
	public function me() {
		$ws = new WeixinAPIService();
		$openId = $ws->getOpenIdFromSession();
		
		if ($openId) {
			$this->initVar();
			
			$this->assign("title", "我");
			
			$es = new ExpressService();
			
			$this->assign("myInfo", $es->getMyInfo($openId));
			
			$this->display();
		} else {
			redirect(__ROOT__ . "/Home");
		}
	}

	/**
	 * 修改我的信息
	 */
	public function editMyInfo() {
		if (IS_POST) {
			$ws = new WeixinAPIService();
			$openId = $ws->getOpenIdFromSession();
			
			$params = array(
					"openId" => $openId,
					"name" => I("post.name"),
					"tel" => I("post.tel"),
					"address" => I("post.address"),
					"bindCode" => I("post.bindCode")
			);
			
			$es = new ExpressService();
			
			$this->ajaxReturn($es->editMyInfo($params));
		}
	}
}